package com.hsnn.medstgmini.base.std.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.StdCompgroup;
import com.hsnn.medstgmini.base.std.model.StdCompgroupLog;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.base.std.service.StdCompgroupManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.AccountUtil;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 集团基础库字典
 * @author jingyu
 * @date 2015-6-9
 */
@Controller
@RequestMapping("/stdCompGroup")
public class StdCompGroupController {
	
	private static final Logger log = Logger.getLogger(StdCompGroupController.class);
	/**
	 * @category 获取user信息
	 * @param 
	 * @return  SysUser
	 */
	public SysUser getUser(){
		return (SysUser) request.getSession().getAttribute(Constants.USERINFO);
	}
	@Autowired
	private StdCompgroupManager stdCompgroupManager;
	@Autowired
	private HttpServletRequest request;
	/**
	 * @category 进入列表页面
	 * @return 集团基础库列表页面
	 */
	@RequestMapping("/compGroupList")
	public String stdCompGroupList() {
		return "/base/std/compGroup";
	}
	/**
	 * @category 进入编辑页面
	 * @return 集团基础库编辑页面
	 */
	@RequestMapping("/compGroupEdit")
	public String stdCompGroupEdit(Model model,String cg) {
		printParams();
		if(cg!=null&&!cg.equals("")){
			StdCompgroup scg=stdCompgroupManager.getCompGroupById(cg);
			model.addAttribute("scg",scg);
		}
		return "/base/std/compGroupEdit";
	}
	/**
	 * @category 进入新增页面
	 * @return 集团基础库新增页面
	 */
	@RequestMapping("/compGroupAdd")
	public String stdCompGroupAdd(Model model,String cg) {
		printParams();
		if(cg!=null&&!cg.equals("")){
			StdCompgroup scg=stdCompgroupManager.getCompGroupById(cg);
			model.addAttribute("scg",scg);
		}
		return "/base/std/compGroupAdd";
	}
	

	/**
	 * @category 提交新增或修改
	 * @param instance
	 * @param userId
	 * @return 新增或修改提交返回结果
	 */
	@RequestMapping(value={"/add","/edit","/submitStdCompGroup"})
	@ResponseBody
	public Pagination submitstdCompGroup(StdCompgroup instance,String userId) {
		printParams();
		Pagination page = new Pagination();


		try {
			if(instance.getCompGroupId().equals("")){
				instance.setCompGroupId(null);
				instance.setStatus((short) 1);
			}else{
				StdCompgroup scp = stdCompgroupManager.getById(instance.getCompGroupId());
				if(instance.getCompGroupName().equals(scp.getCompGroupName())&&instance.getCompGroupShortname().equals(scp.getCompGroupShortname())&&instance.getRemark().equals(scp.getRemark())){
					page.setSuccess(false);
					page.setMsg("数据未做任何修改，不能保存！");
					return page;
				}
			}
			
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			instance.setUpdDatetime(new Timestamp(new Date().getTime()));
			if(!stdCompgroupManager.checkCompGroupName(instance)){
				page.setSuccess(false);
				page.setMsg("集团名称已存在，请重新输入");
				return page;				
			}
			instance.setUpdUser(user.getId());
			if(StringUtils.isBlank(instance.getCompGroupCode())){
				instance.setCompGroupCode(AccountUtil.getStdSequence(Constants.STD_JITUAN_PREFIX, Constants.STD_JITUAN, Constants.STD_JITUAN_LEN));
			}
			
			stdCompgroupManager.attachDirty(instance);
			page.setMsg(instance.getCompGroupCode());
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		} catch(Error error) {
			error.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 
	 * @category 查看集团库
	 * @Auther 徐国鹏
	 * @date 2015年9月22日 上午9:15:17
	 * @param stdCompinfo
	 * @return
	 * @return Pagination
	 */
	@RequestMapping("/stdCompGroupList")
	@ResponseBody
	public Pagination getStdCompinfoList(StdCompgroup stdCompgroup) {
		printParams();
		Pagination page = new Pagination(request);
		try {
			page = stdCompgroupManager.queryStdCompinfoList(page, stdCompgroup);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Error error) {
			error.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * 
	 * @category 停用、启用
	 * @Auther 徐国鹏
	 * @date 2015年9月22日 上午9:14:40
	 * @param array
	 * @return
	 * @return Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			int sum = 0;
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<StdCompgroup>>() {
				}.getType();
				List<StdCompgroup> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (StdCompgroup dds : list) {
						dds.setUpdUser(user.getId());
						int count = stdCompgroupManager.batchStarts(dds);
						sum += count;
					}
					page.getConditions().put("sum", sum+"");
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * @category 进入维护记录列表页面
	 * @param model
	 * @param tid
	 * @return 集团基础库维护记录列表页面
	 */
	@RequestMapping("/stdCompGroupLog")
	public String stdCompGroupLog(Model model,String tid) {
		printParams();
		model.addAttribute("compGroupId",tid);
		request.setAttribute("compGroupCode", request.getParameter("compGroupCode"));
		try {
			String compGroupName = new String(request.getParameter("compGroupName").getBytes("iso8859-1"),"utf-8");
			request.setAttribute("compGroupName", compGroupName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/base/std/compGroupLog";
	}
	
	
	/**
	 * @category 进入维护记录详情页面
	 * @param model
	 * @param tid
	 * @return 集团基础库维护记录详情页面
	 */
	
	@RequestMapping("/toDicDrugformLogDetail")
	public String toDicDrugformLogDetail(){
		printParams();
		Pagination  page = new Pagination();
		page.getConditions().put("logId", request.getParameter("logId"));
		List<Map<String,Object>> list = stdCompgroupManager.getDicDrugformLogDetail(page);
		// --------begin
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		String[] cColunm = {"集团编码","集团名称","集团简称","备注","状态"};
		String[] eColunm = {"compGroupCode","compGroupName","compGroupShortname","remark","status"};
		for(int i = 0;i<cColunm.length;i++){
			Map<String,Object> map =  new HashMap<String,Object>();
			map.put("colunm", cColunm[i]);//字段名
			map.put("after", !"status".equals(eColunm[i])?list.get(0).get(eColunm[i]):"1".equals(list.get(0).get(eColunm[i]).toString())?"启用":"停用");//修改后数据
			map.put("before", list.size()==1?null:!"status".equals(eColunm[i])?list.get(1).get(eColunm[i]):"1".equals(list.get(1).get(eColunm[i]).toString())?"启用":"停用");//修改前数据
			if(list.size()==1){
				map.put("red", "1");//是否变红加粗 1是 0 否
			}else{
				//判断修改后与修改前数据是否相等
				if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
					map.put("red", "1");
				}else{
					map.put("red", "0");
				}
			}
			mapList.add(map);
		}
		for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
			if("1".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		for(int i = 0;i<mapList.size();i++){
			if("0".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		request.setAttribute("dataList", dataList);
		// --------end
		request.setAttribute("list", list);
		return "/base/std/compGroupLogDetailList";
		
	}
	
	/**
	 * 集团库  维护记录查询及条件查询
	 * 
	 * 用来封装json
	 *  
	 * @param request
	 * @param result
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/stdCompinfoLogList")
	@ResponseBody
	@JsonIgnore
	public Pagination getstdCompinfoLogList(HttpServletRequest request,String date1,String date2) {
		printParams();
		Pagination page = new Pagination(request);
		StdCompgroupLog stdCompgroupLog = new StdCompgroupLog();

		try {
			String compGroupId = request.getParameter("compGroupId");
			stdCompgroupLog.setCompGroupId(compGroupId);
			stdCompgroupLog.setDate1(date1);
			stdCompgroupLog.setDate2(date2);
			List list = stdCompgroupManager.queryStdCompinfoLogByName(page,stdCompgroupLog);
			page.setRecords(stdCompgroupLog.getCount());
			page.setRows(list);
		} catch (Exception e) {
			e.printStackTrace();
		} catch (Error error) {
			error.printStackTrace();
		}
		return page;
	}
	
	/**
	 * @category 进入下属企业列表页面
	 * @param model
	 * @param tid
	 * @return 集团基础库维护记录列表页面
	 */
	@RequestMapping("/stdCompGroupSubC")
	public String stdCompGroupSubC(Model model,String tid) {
		printParams();
		model.addAttribute("compGroup",stdCompgroupManager.getCompGroupById(tid));
		return "/base/std/compGroupSubCList";
	}
	
	/**
	 * @category 分页获取下属企业列表json
	 * @param result
	 * @param tid
	 * @return 下属企业列表json
	 */
	@RequestMapping("querystdCompGroupSubCJson")
	@ResponseBody
	public Pagination querystdCompGroupSubCJson(String tid) {
		printParams();
		Pagination page = new Pagination(request);
		String compCode = request.getParameter("compCode");
		String compName = request.getParameter("compName");
		
		page.getConditions().put("compGroupId", tid);
		page.getConditions().put("compCode", compCode);
		page.getConditions().put("compName", compName);
		try{
			page = stdCompgroupManager.getCompListByBroupId(page);		
		} catch(Error error) {
			error.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * @category 分页获取无集团id的企业列表json
	 * @param result
	 * @param tid
	 * @return 下属企业列表json
	 */
	@RequestMapping("compListNotGJson")
	@ResponseBody
	public Pagination querystdCompGroupSubCJson(String code,String name) {
		printParams();
		Pagination page = new Pagination(request);
		if(code!=null&&!StringUtils.isEmpty(code)){
			page.getConditions().put("compCode", code);
		}
		if(name!=null&&!StringUtils.isEmpty(name)){
			page.getConditions().put("compName", name);
		}
		page.getConditions().put("compGroupId", null);
		try{
		  page = stdCompgroupManager.getStdCompinfoListButHB(page);		
		} catch(Error error) {
			error.printStackTrace();
			page.setSuccess(false);;
		}
		return page;
	}
	
	/**
	 * @category 批量关联与取消集团下属企业
	 * @param result
	 * @param tid
	 * @return 下属企业列表json
	 */
	@RequestMapping("batchGroupAddComp")
	@ResponseBody
	public Pagination batchGroupAddComp(String compinfos) {
		printParams();
		Pagination page = new Pagination(request);
		try {
			if (compinfos != null && !"".equals(compinfos)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<StdCompinfo>>() {
				}.getType();
				List<StdCompinfo> list = gson.fromJson(compinfos, type);
				stdCompgroupManager.batchGroupAddComp(list);
				page.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		} catch(Error error) {
			error.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * @category 进入集团详情页面
	 * @param model
	 * @param tid
	 * @return 集团详情页面
	 */
	@RequestMapping("/toGroupDetail")
	public String toGroupDetail(Model model,String tid) {
		printParams();
		model.addAttribute("compGroup",stdCompgroupManager.getCompGroupById(tid));
		return "/base/std/compGroupDetail";
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String compGroupCode = request.getParameter("compGroupCode");
		String compGroupName = request.getParameter("compGroupName");
		String compGroupShortname = request.getParameter("compGroupShortname");
		String remark = request.getParameter("remark");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(compGroupCode)){
			page.getConditions().put("compGroupCode", compGroupCode.trim());
		}
		if(StringUtils.isNotBlank(compGroupName)){
			page.getConditions().put("compGroupName", compGroupName.trim());
		}
		if(StringUtils.isNotBlank(compGroupShortname)){
			page.getConditions().put("compGroupShortname", compGroupShortname.trim());
		}
		if(StringUtils.isNotBlank(remark)){
			page.getConditions().put("remark", remark.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String("集团库.xls".getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
		     stdCompgroupManager.exportExcel(page,os);

		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
